<template lang="">
  <div class="header">
    <div class="lnner-header">
      <div style="margin-top: 230px;">
        <h2>欢迎来到vue-E-commerce system!</h2>
        <el-card shadow="never">
          <el-form ref="loginForm" label-position="top" status-icon :rules="rules" :model="formLogin" size="default"
            style="width: 400px;">
            <el-form-item prop="username">
              <el-input type="text" @keyup.enter.native="handleBindPhone" v-model="formLogin.username" placeholder="用户名"
                clearable>
                <i slot="prepend" class="el-icon-user-solid"></i>
              </el-input>
            </el-form-item>
            <el-form-item prop="password">
              <el-input @keyup.enter.native="handleBindPhone" type="password" v-model="formLogin.password"
                placeholder="密码" show-password clearable>
                <i slot="prepend" class="el-icon-key"></i>
              </el-input>
            </el-form-item>
            <el-form-item prop="yzm">
              <el-input type="text" v-model="formLogin.yzm" @keyup.enter.native="handleBindPhone" placeholder="验证码"
                clearable style="width: 70%;">
                <i slot="prepend" class="layui-icon">&#xe679;</i>
              </el-input>
              <img src="api/api/captcha" style="width: 30%; height: 40px; cursor: pointer;" class='switch'>
            </el-form-item>
            <p>
              <el-checkbox v-model="checked" class="remeberPwd">记住密码</el-checkbox>
              <span
                style="color: #409EFF;padding-left: 250px;line-height: 19px;font-size: 14px;cursor: pointer;">忘记密码?</span>
            </p>
            <el-button size="default" @click="handleBindPhone" type="primary" :loading="logining" class="button-login"
              style="width: 100%" @keydown="show($event)">登录
            </el-button>
          </el-form>
        </el-card>
      </div>
    </div>
    <!-- 波浪区域 -->
    <div>
      <!-- svg形状 -->
      <svg class="waves" viewBox="0 24 150 28" preserveAspectRatio="none" shape-rendering="auto">
        <!-- 形状容器 -->
        <defs>
          <path id="gentle-wave" d="M-160 44c30 0 58-18 88-18s 58 18 88 18 58-18 88-18 58 18 88 18 v44h-352z" />
        </defs>
        <!-- 组合形状 -->
        <g class="parallax">
          <use xlink:href="#gentle-wave" x="48" y="0" fill="rgba(255,255,255,0.7" />
          <use xlink:href="#gentle-wave" x="48" y="3" fill="rgba(255,255,255,0.5)" />
          <use xlink:href="#gentle-wave" x="48" y="5" fill="rgba(255,255,255,0.3)" />
          <use xlink:href="#gentle-wave" x="48" y="7" fill="#fff" />
        </g>
      </svg>
    </div>

  </div>


</template>
<script>
    //远程js
    //https://webapi.amap.com/maps?v=1.4.15&key=78d9fe7e7c5817a03e0a80b562995fdb
    import '../../assets/js/maps'
    import jquery from 'jquery'
    export default {
        data() {
            return {
                timeInterval: null,
                logining: false,

                // 表单校验
                rules: {
                    username: [{
                        required: true,
                        message: '请输入用户名',
                        messtrigger: 'blur',
                        trigger: 'blur'
                    }, {
                        required: true,
                        pattern: /^(\w){4,12}$/,
                        message: '只能输入4-12个字母、数字、下划线 ',
                        trigger: 'blur'
                    }],
                    password: [{
                        required: true,
                        messtrigger: 'blur',
                        message: '请输入密码',
                        trigger: 'blur'
                    }, {
                        required: true,
                        pattern: /^.*(?=.{6,})(?=.*\d)(?=.*[A-Z])(?=.*[a-z])(?=.*[!@#$%^&*? ]).*$/,
                        message: '最少6位，包括至少1个大写字母，1个小写字母，1个数字，1个特殊字符',
                        trigger: 'blur'
                    }],
                    yzm: [{
                        required: true,
                        messtrigger: 'blur',
                        message: '请输入验证码',
                        trigger: 'blur'
                    }]
                },
                // 表单
                formLogin: {
                    username: "",
                    password: "",
                    yzm: ""
                },
                // 记住密码checked
                checked: true,
                //存储用户地理位置
                wz: {
                    formattedAddress: '',
                    position: {
                        lng: '',
                        lat: ''
                    }
                }
            };
        },

        mounted() {
            this.account(); //获取cookie的方法
            jquery('.switch').click(function() {
                jquery(this).attr('src', `api/api/captcha?id=${Math.random()}`);
            });


            //获取用户地理位置信息
            this.getLocation();
        },
        methods: {
            //获取地理位置
            getLocation() {
                const self = this
                AMap.plugin('AMap.Geolocation', function() {
                    var geolocation = new AMap.Geolocation({
                        // 是否使用高精度定位，默认：true
                        enableHighAccuracy: true,
                        // 设置定位超时时间，默认：无穷大
                        timeout: 10000,
                    })

                    geolocation.getCurrentPosition()
                    AMap.event.addListener(geolocation, 'complete', onComplete);
                    AMap.event.addListener(geolocation, 'error', onError);

                    function onComplete(data) {
                        self.wz.formattedAddress = data.formattedAddress;
                        self.wz.position.lng = data.position.lng;
                        self.wz.position.lat = data.position.lat;
                    }

                    function onError(data) {
                        // 定位出错
                        console.log('定位失败错误：', data);
                        // 调用ip定位
                        self.getLngLatLocation();
                    }
                })
            },
            //ip定位
            getLngLatLocation() {

                const self = this
                AMap.plugin('AMap.CitySearch', function() {
                    var citySearch = new AMap.CitySearch();
                    citySearch.getLocalCity(function(status, result) {
                        if (status === 'complete' && result.info === 'OK') {
                            // 查询成功，result即为当前所在城市信息
                            console.log('通过ip获取当前城市：', result)
                            self.wz.formattedAddress = result.province + result.city;
                            self.wz.position.lng = result.rectangle;

                            //逆向地理编码
                            AMap.plugin('AMap.Geocoder', function() {
                                var geocoder = new AMap.Geocoder({
                                    // city 指定进行编码查询的城市，支持传入城市名、adcode 和 citycode
                                    city: result.adcode

                                })

                                var lnglat = result.rectangle.split(';')[0].split(',');
                                geocoder.getAddress(lnglat, function(status, data) {
                                    if (status === 'complete' && data.info === 'OK') {
                                        // result为对应的地理位置详细信息
                                        console.log(data)
                                        AMap.plugin('AMap.Weather', function() {
                                            //创建天气查询实例
                                            var weather = new AMap.Weather();
                                            //执行实时天气信息查询
                                            weather.getLive(result.city, function(err, data) {
                                                console.log(err, data);

                                            });
                                        });

                                    }
                                })
                            })
                        }
                    })

                })


            },
            //记住密码保存到cookie
            account() {

                // if (document.cookie.length <= 0) {
                this.formLogin.username = this.getCookie("username");
                this.formLogin.password = this.getCookie("password");
                // }
            },
            setCookie(c_name, c_pwd, exdate) {
                //账号，密码 ，过期的天数
                var exdate = new Date();

                exdate.setTime(exdate.getTime() + 24 * 60 * 60 * 1000 * exdate); //保存的天数
                document.cookie =
                    "username=" + c_name + ";path=/;expires=" + exdate.toLocaleString();
                document.cookie =
                    "password=" + c_pwd + ";path=/;expires=" + exdate.toLocaleString();
            },
            getCookie(name) {
                var arr = document.cookie.split(";");
                //["_ga=GA1.1.1756734561.1561034020", " mobile=123" password=456"]
                for (var i = 0; i < arr.length; i++) {
                    var arr2 = arr[i].split("="); // ["_ga", "GA1.1.1756734561.1561034020"]
                    if (arr2[0].trim() == name) {
                        return arr2[1];
                    }
                }
            },
            clearCookie() {
                this.setCookie("", "", -1); //清除cookie
            },
            // 提交登录信息
            handleBindPhone() {
                this.$refs.loginForm.validate(valid => {
                    if (valid) {
                        this.logining = true;
                        var _this = this;
                        if (_this.checked == true) {
                            //存入cookie
                            _this.setCookie(
                                _this.formLogin.username,
                                _this.formLogin.password,
                                7
                            ); //保存7天
                        } else {
                            _this.clearCookie();
                        }

                        // 登录
                        // 注意 这里的演示没有传验证码
                        // 具体需要传递的数据请自行修改代码
                        setTimeout(() => {
                            this.$axios({
                                method: 'post',
                                url: `api/login`,
                                data: {
                                    username: _this.formLogin.username,
                                    password: _this.formLogin.password,
                                    yzm: _this.formLogin.yzm,
                                }
                            }).then((res) => {

                                if (res.data.data == '验证码错误(小写字母)') {
                                    jquery('.switch').attr('src', `api/api/captcha?id=${Math.random()}`);
                                }
                                if (res.data.data == '登录成功') {
                                    this.$message({
                                        message: '登录成功',
                                        type: 'success'
                                    });
                                    this.$cookie.set('user', _this.formLogin.username, '1min')
                                        //发送请求添加地理位置
                                    return this.$axios.put(`api/xx/${this.$cookie.get('user')}`, {
                                        dz: _this.wz.formattedAddress,
                                        lng: _this.wz.position.lng,
                                        lat: _this.wz.position.lat
                                    }).then(res => {
                                        this.$router.push({
                                            path: '/home'
                                        });
                                    })

                                    window.sessionStorage.setItem('token', res.data.token)
                                } else {
                                    const h = this.$createElement;
                                    this.$notify.error({
                                        title: '错误',
                                        message: h('i', {
                                            style: 'color: red'
                                        }, res.data.data)
                                    });
                                }
                                this.logining = false;
                            }).catch(error => {
                                console.log(error);
                            });
                        }, 1000);
                    } else {
                        // 登录表单校验失败
                        this.$message.error("表单校验失败，请检查");
                        return false;
                    }
                });
            }
        },
        show(e) {
            if (e.keyCode == 13) {
                this.handleBindPhone()
            }
        }
    }
</script>
<style lang="less">
    .header {
        position: relative;
        /* 背景渐变 */
        background: linear-gradient(60deg, rgba(84, 58, 183, 1) 0%, rgba(0, 172, 193, 1) 100%);
        color: wheat;
    }
    
    .lnner-header {
        width: 100%;
        /* flex */
        /* 垂直居中 */
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
    }
    
    h2 {
        text-align: center;
        font-family: 'Lato', 'sans-serif';
        font-weight: 300;
        /* font-spacing:2px; */
        font-size: 28px;
    }
    
    .waves {
        position: relative;
        width: 100%;
        height: 15vh;
        margin-bottom: -7px;
        /* 最小值 */
        min-height: 100px;
        /* 最大值 */
        max-height: 150px;
    }
    
    .parallax>use {
        animation: move-forever 25s cubic-bezier(.55, .5, .45, .5) infinite;
    }
    /* 选择的一个use */
    
    .parallax>use:nth-child(1) {
        /* 延迟 2s 执行 */
        animation-delay: 1s;
        /* 7s 内 执行完毕 */
        animation-duration: 7s;
    }
    
    .parallax>use:nth-child(2) {
        animation-delay: -3s;
        animation-duration: 10s;
    }
    
    .parallax>use:nth-child(3) {
        animation-delay: -4s;
        animation-duration: 13s;
    }
    
    .parallax>use:nth-child(4) {
        animation-delay: -5s;
        animation-duration: 20s;
    }
    
    @keyframes move-forever {
        0% {
            transform: translate3d(-90px, 0, 0);
        }
        100% {
            transform: translate3d(85px, 0, 0);
        }
    }
</style>